<?php

/**
 * Application Model Mappers
 *
 * @package Application_Model
 * @subpackage Mapper
 * @author <YOUR NAME HERE>
 * @copyright ZF model generator
 * @license http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * Data Mapper implementation for Application_Model_Sondage
 *
 * @package Application_Model
 * @subpackage Mapper
 * @author <YOUR NAME HERE>
 */
class Application_Model_Mapper_Sondage extends Application_Model_Mapper_MapperAbstract
{
 /**
     * Returns an array, keys are the field names.
     *
     * @param Application_Model_Sondage $model
     * @return array
     */
    public function toArray($model)
    {
        if (! $model instanceof Application_Model_Sondage) {
            throw new Exception('Unable to create array: invalid model passed to mapper');
        }

        $result = array(
            'idsondage' => $model->getIdsondage(),
            'titre' => $model->getTitre(),
            'description' => $model->getDescription(),
            'date_creation' => $model->getDateCreation(),
            'date_publication' => $model->getDatePublication(),
            'domaine_iddomaine' => $model->getDomaineIddomaine(),
            'sondagepersonne_idsondagepersonne' => $model->getSondagepersonneIdsondagepersonne(),
            'activation' => $model->getActivation(),
        );

        return $result;
    }

    /**
     * Returns the DbTable class associated with this mapper
     *
     * @return Application_Model_DbTable_Sondage
     */
    public function getDbTable()
    {
        if ($this->_dbTable === null) {
            $this->setDbTable('Application_Model_DbTable_Sondage');
        }

        return $this->_dbTable;
    }

    /**
     * Deletes the current model
     *
     * @param Application_Model_Sondage $model The model to delete
     * @see Application_Model_DbTable_TableAbstract::delete()
     * @return int
     */
    public function delete($model)
    {
        if (! $model instanceof Application_Model_Sondage) {
            throw new Exception('Unable to delete: invalid model passed to mapper');
        }

        $this->getDbTable()->getAdapter()->beginTransaction();
        try {
            $where = $this->getDbTable()->getAdapter()->quoteInto('idsondage = ?', $model->getIdsondage());
            $result = $this->getDbTable()->delete($where);

            $this->getDbTable()->getAdapter()->commit();
        } catch (Exception $e) {
            $this->getDbTable()->getAdapter()->rollback();
            $result = false;
        }

        return $result;
    }

    /**
     * Saves current row, and optionally dependent rows
     *
     * @param Application_Model_Sondage $model
     * @param boolean $ignoreEmptyValues Should empty values saved
     * @param boolean $recursive Should the object graph be walked for all related elements
     * @param boolean $useTransaction Flag to indicate if save should be done inside a database transaction
     * @return boolean If the save action was successful
     */
    public function save(Application_Model_Sondage $model,
        $ignoreEmptyValues = true, $recursive = false, $useTransaction = true
    ) {
        $data = $model->toArray();
        if ($ignoreEmptyValues) {
            foreach ($data as $key => $value) {
                if ($value === null or $value === '') {
                    unset($data[$key]);
                }
            }
        }

        $primary_key = $model->getIdsondage();
        $success = true;

        if ($useTransaction) {
            $this->getDbTable()->getAdapter()->beginTransaction();
        }

        unset($data['idsondage']);

        try {
            if ($primary_key === null) {
                $primary_key = $this->getDbTable()->insert($data);
                if ($primary_key) {
                    $model->setIdsondage($primary_key);
                } else {
                    $success = false;
                }
            } else {
                $this->getDbTable()
                     ->update($data,
                              array(
                                 'idsondage = ?' => $primary_key
                              )
                );
            }

            if ($recursive) {
                if ($success && $model->getParticipation(false) !== null) {
                    $Participation = $model->getParticipation();
                    foreach ($Participation as $value) {
                        $success = $success &&
                            $value->setSondageIdsondage($primary_key)
                                  ->save($ignoreEmptyValues, $recursive, false);

                        if (! $success) {
                            break;
                        }
                    }
                }

                if ($success && $model->getQuestion(false) !== null) {
                    $Question = $model->getQuestion();
                    foreach ($Question as $value) {
                        $success = $success &&
                            $value->setSondageIdsondage($primary_key)
                                  ->save($ignoreEmptyValues, $recursive, false);

                        if (! $success) {
                            break;
                        }
                    }
                }

            }

            if ($useTransaction && $success) {
                $this->getDbTable()->getAdapter()->commit();
            } elseif ($useTransaction) {
                $this->getDbTable()->getAdapter()->rollback();
            }

        } catch (Exception $e) {
            if ($useTransaction) {
                $this->getDbTable()->getAdapter()->rollback();
            }

            $success = false;
        }

        return $success;
    }

    /**
     * Finds row by primary key
     *
     * @param int $primary_key
     * @param Application_Model_Sondage|null $model
     * @return Application_Model_Sondage|null The object provided or null if not found
     */
    public function find($primary_key, $model)
    {
        $result = $this->getRowset($primary_key);

        if (is_null($result)) {
            return null;
        }

        $row = $result->current();

        $model = $this->loadModel($row, $model);

        return $model;
    }

    /**
     * Loads the model specific data into the model object
     *
     * @param Zend_Db_Table_Row_Abstract|array $data The data as returned from a Zend_Db query
     * @param Application_Model_Sondage|null $entry The object to load the data into, or null to have one created
     * @return Application_Model_Sondage The model with the data provided
     */
    public function loadModel($data, $entry)
    {
        if ($entry === null) {
            $entry = new Application_Model_Sondage();
        }

        if (is_array($data)) {
            $entry->setIdsondage($data['idsondage'])
                  ->setTitre($data['titre'])
                  ->setDescription($data['description'])
                  ->setDateCreation($data['date_creation'])
                  ->setDatePublication($data['date_publication'])
                  ->setDomaineIddomaine($data['domaine_iddomaine'])
                  ->setSondagepersonneIdsondagepersonne($data['sondagepersonne_idsondagepersonne'])
                  ->setActivation($data['activation']);
        } elseif ($data instanceof Zend_Db_Table_Row_Abstract || $data instanceof stdClass) {
            $entry->setIdsondage($data->idsondage)
                  ->setTitre($data->titre)
                  ->setDescription($data->description)
                  ->setDateCreation($data->date_creation)
                  ->setDatePublication($data->date_publication)
                  ->setDomaineIddomaine($data->domaine_iddomaine)
                  ->setSondagepersonneIdsondagepersonne($data->sondagepersonne_idsondagepersonne)
                  ->setActivation($data->activation);
        }

        $entry->setMapper($this);

        return $entry;
    }
    
    public function getsondage($id){
    
    	$identity=Zend_Auth::getInstance()->getIdentity();
    	
    	$selector=$this->getDbTable()->select(Zend_Db_Table::SELECT_WITH_FROM_PART);
    
    	$selector->setIntegrityCheck(false);
    
    	$selector->joinLeft("question", "question.sondage_idsondage=sondage.idsondage");
    	$selector->joinLeft("reponse", "reponse.Question_idQuestion=question.idQuestion");
    
    	$selector->order("ordrequestion");
    	
    	if($identity->role=="admin"){
    		$selector->where("  question.sondage_idsondage = $id AND activation=1");
    	}else {
    		$selector->where("  question.sondage_idsondage = $id");
    	}
    
    	/*echo $selector;
    	 die();*/
    	$reponse= $this->getDbTable()->fetchAll($selector)->toArray();
    
    
    	$sondage=array();
    	foreach ($reponse as $key => $value){
    		 
    		$question['id']=$value["idQuestion"];
    		$question['label']=$value["textquestion"];
    		$question['score']=$value["score"];
    		$sondage[$value['idQuestion']]['question']=$question;
    		 
    
    		if(!empty($value['labelrepense'])){
    			$reponsevalue['id']=$value['idreponse'];
    			$reponsevalue['label']=$value['labelrepense'];
    			$reponsevalue['type']=$value['typereponse_idtypereponse'];
    			$reponsevalue['value']=$value['repensevrai'];
    			$reponsevalue['score']=$value['score'];
    			$sondage[$value['idQuestion']]['reponses'][]=$reponsevalue;
    		}
    
    		 
    		 
    	}
    	//echo"<pre>"; print_r($sondage);echo"</pre>";
    	return $sondage;
    
    }
    
    public function getSondageParticiper($id){
    	
    	
    	$selector_all=$this->getDbTable()->select(Zend_Db_Table::SELECT_WITH_FROM_PART);
    	$selector_all->setIntegrityCheck(false);
    	$selector_all->joinLeft("participation", "participation.sondage_idsondage=sondage.idsondage");
    	$selector_all->joinLeft("sondagepersonne", "sondagepersonne.idsondagepersonne=participation.sondagepersonne_idsondagepersonne");
    	$selector_all->joinLeft("reponseparticipant", "participation.idparticipation=reponseparticipant.participation_idparticipation");
    	$selector_all->where(" sondagepersonne.idsondagepersonne = $id");
    
    
    	$result1= $this->getDbTable()->fetchAll($selector_all)->toArray();
    	
    	$selector=$this->getDbTable()->select(Zend_Db_Table::SELECT_WITH_FROM_PART);
    	$selector->setIntegrityCheck(false);
    	
    	
    	$sbslect="
    	(SELECT idsondage   FROM `sondage` 
    	LEFT JOIN `participation` ON participation.sondage_idsondage=sondage.idsondage 
    	LEFT JOIN `sondagepersonne` ON sondagepersonne.idsondagepersonne=participation.sondagepersonne_idsondagepersonne 
    	LEFT JOIN `reponseparticipant` ON participation.idparticipation=reponseparticipant.participation_idparticipation 
    	WHERE ( sondagepersonne.idsondagepersonne = $id))";
    	
    	
    	$selector->where(" idsondage NOT IN(".$sbslect.")");
    	//echo $selector->__toString();
    	//die();
    	$result2= $this->getDbTable()->fetchAll($selector)->toArray();
    	
    	return array_merge($result2,$result1);
    	
    }

    
    public function getSondageResult($id){
    	
    	$selector=$this->getDbTable()->select(Zend_Db_Table::SELECT_WITH_FROM_PART);
    
    	$selector->setIntegrityCheck(false);
    
    	$selector->join("participation", "participation.sondage_idsondage=sondage.idsondage");
    	$selector->join("sondagepersonne", "sondagepersonne.idsondagepersonne=participation.sondagepersonne_idsondagepersonne");
    
    	$selector->where(" participation.sondage_idsondage = $id AND ( scorefinal IS NOT NULL OR scorefinal <> 0 ) ");
    
    	$selector->order("scorefinal DESC");
    	$data=$this->getDbTable()->fetchAll($selector);
    	if($data){
    		return $data->toArray();
    	}else{
    		return array();
    	}
    	///return $this->getDbTable()->fetchAll($selector)->toArray() ;
    
    }
    
    public function ispasser($idpersonne, $idsondage){
    	$selector_all=$this->getDbTable()->select(Zend_Db_Table::SELECT_WITH_FROM_PART);
    	$selector_all->setIntegrityCheck(false);
    	$selector_all->joinLeft("participation", "participation.sondage_idsondage=sondage.idsondage");
    	$selector_all->joinLeft("sondagepersonne", "sondagepersonne.idsondagepersonne=participation.sondagepersonne_idsondagepersonne");
    	$selector_all->joinLeft("reponseparticipant", "participation.idparticipation=reponseparticipant.participation_idparticipation");
    	$selector_all->where(" sondagepersonne.idsondagepersonne = $idpersonne AND participation.sondage_idsondage= $idsondage");
    	
    	
    	$data=$this->getDbTable()->fetchAll($selector_all);
    	if($data){
    		return $data->toArray();
    	}else{
    		return array();
    	}
    //	return  $this->getDbTable()->fetchRow($selector_all)->toArray();
    }
   
    
    
}
